#
# ShoeBox
#  A start product for Plone - ShoeBox
#
# ShoeBox.py
#  The Product
#
# Author: Christian Koller <admin@iecw.net>
#
# Released under GNU GPL v2 or later
#
from zLOG import LOG, INFO

from Products.Archetypes.public import *
from Products.ShoeBox.config import PROJECTNAME
from Products.CMFCore import CMFCorePermissions
from Products.validation import V_REQUIRED
from AccessControl import ClassSecurityInfo
from DocumentTemplate import sequence

from Products.ShoeBox.config import PROJECTNAME

class ShoeBoxAccount(BaseFolder):
    """ Shoe Box account """
    meta_type = 'ShoeBoxAccount'
    
    security  = ClassSecurityInfo()
    
    _at_rename_after_creation = True
    
    allowed_content_types = (
            'ShoeBoxEntry',
            )
    
    ##
    ##  The Schema includes two variables, on for the Repository itself and one for a Path within the Repository
    ##
    
    ## Set the icon for the ShoeBox
    content_icon = 'shoebox.png'
    
    ##
    ##  Redefine the view tab (action) for ShoeBox
    ##
    actions = (
            {
                    'id': 'view',
                    'name': 'View',
                    'action': 'string:${object_url}/shoeboxaccount_view',
                    'permissions': (CMFCorePermissions.View,),
                    'category':'object',
            },
    )
    
    def getEntries(self, removeOrphans=True):
        """
        Return the account entries for this account
        """
        entries = self.getFolderContents(batch=False,
            contentFilter={'portal_type' : 'ShoeBoxEntry'}, full_objects=True)
        if removeOrphans:
            for e in entries:
                if e.account != self.id:
                    entries.remove(e)
        entries = sequence.sort(entries, (('date','cmp'),))
        return entries
    
    def initializeArchetype(self, **kwargs):
        BaseFolder.initializeArchetype(self, **kwargs)
        LOG("ShoeBoxAccount",INFO, "initializeArchetype")
        
    def at_post_edit_script(self):
        entries = self.getEntries(False)
        for e in entries:
            e.account = self.id
            e.update()
        
    def getSummary(self):
        """
        Returns the summary of transactions
        [in, out, balance]
        """
        entries = self.getEntries()
        inComing = 0
        outGoing = 0
        for e in entries:
            if e.direction == 'Incoming':
                inComing += e.getAmount()
            else:
                outGoing += e.getAmount()
        balance = inComing - outGoing
        return [inComing, outGoing, balance]
## Register the new type within Zope
registerType(ShoeBoxAccount,PROJECTNAME)
